var cartVue = new Vue({
	el: "body",
	data: {
		cartList: [],
		checkedAll: false,
		totalPrice: 0,
		kind: 0,
		isLoading:true
	},
	created: function() {
		init();
		_this = this;
		verifyLogin(_this); //验证用户是否登录
	},
	methods: {
		addNum: function(a) {
			_this.cartList[a].num++;
			updateNum(a, _this)
			_this.countTotalPrice()
		},
		deleteNum: function(a) {
			if(_this.cartList[a].num <= 1) {
				_this.cartList[a].num = 1
				alert("至少选中一件")
			} else {
				_this.cartList[a].num--;
			}
			updateNum(a, _this)
			_this.countTotalPrice()
		},
		deleteProduct: function(a) {
			deleteProduct(a, _this)
			_this.cartList.splice(a, 1) //从vue实例中删除
			_this.countTotalPrice()
		},
		selectProduct: function(item) {
			if(typeof item.checked == "undefined") { //判断有没有判断选中的标志
				Vue.set(item, "checked", true);
			} else {
				item.checked = !item.checked;
			};
			if(item.checked == false) { //判断有没有判断选中的标志
				_this.checkedAll = false;
			};
			var num = 0;
			for(var i = 0; i < _this.cartList.length; i++) {
				if(_this.cartList[i].checked == true) {
					num++
				}
			}
			if(num == _this.cartList.length) {
				_this.checkedAll = true;
			}
			panduan(_this)
			_this.countTotalPrice()
		},
		selectAll: function() {
			_this.checkedAll = !_this.checkedAll;
			_this.cartList.forEach(function(item, index) {
				if(typeof item.checked == "undefined") {
					Vue.set(item, "checked", _this.checkedAll);
				} else {
					item.checked = _this.checkedAll;
				}

			})
			panduan(_this)
			_this.countTotalPrice()
		},
		countTotalPrice: function() {
			_this.totalPrice = 0
			var total = 0
			_this.cartList.forEach(function(item, index) {
				if(item.checked) {
					total += item.num * item.attributes.price[0]
					_this.totalPrice = total.toFixed(2)
				}
			})
		},
		payCart: function() {
			var paylist = []
			var imglist =[]
			var total = 0
			var all = 0
			_this.cartList.forEach(function(item, index) {
				if(item.checked) {
					total += item.num * item.attributes.price[0]
					paylist.push(item.attributes.pid)
					imglist.push(item.attributes.image[0])
					all += item.num
					_this.totalPrice = total.toFixed(2)
				}
			})
			if(paylist == []) {
				alert("至少结算一件商品")
			} else {
				payProducts(paylist, _this.totalPrice, all,imglist)
			}
		}
	}
})

function verifyLogin(t) {
	currentUser = AV.User.current();
	if(currentUser) {
		loadCart(t)
	} else {
		location.href = "login.html?RetUrl=" + getPageUrl()
	}
}

function loadCart(a) {
	var username = currentUser.attributes.username
	var query = new AV.Query('Cart');
	query.equalTo("username", username);
	query.find().then(function(products) {
		for(var i = 0; i < products.length; i++) {
			var num = products[i].attributes.num
			var cartId = products[i].attributes.pid
			searchFavItem(cartId, a, num)
		}
		a.isLoading=false
	}).catch(function(error) {
		console.log(JSON.stringify(error));
	});
}

function searchFavItem(a, b, c) {
	var query = new AV.Query('Product');
	query.equalTo("pid", a);
	query.find().then(function(products) {
		products[0]["num"] = c
		b.cartList.push(products[0])
	}).catch(function(error) {
		console.log(JSON.stringify(error));
	});
}

function updateNum(t, x) {
	var pid = x.cartList[t].attributes.pid
	var query = new AV.Query('Cart');
	query.equalTo("pid", pid);
	query.find().then(function(products) {
		var rid = products[0].id
		var todo = AV.Object.createWithoutData('Cart', rid);
		todo.set('num', x.cartList[t].num);
		// 保存到云端
		todo.save();
	}).catch(function(error) {
		console.log(JSON.stringify(error));
	});
}

function deleteProduct(t, x) {
	var pid = x.cartList[t].attributes.pid
	var query = new AV.Query('Cart');
	query.equalTo("pid", pid);
	query.find().then(function(products) {
		var rid = products[0].id
		var todo = AV.Object.createWithoutData('Cart', rid);
		todo.destroy().then(function(success) {
			alert("删除成功") // 删除成功
		}, function(error) {
			// 删除失败
		});
	}).catch(function(error) {
		console.log(JSON.stringify(error));
	});
}

function panduan(a) {
	var n = 0
	for(var i = 0; i < a.cartList.length; i++) {
		if(a.cartList[i].checked == true) {
			n++
		}
	}
	a.kind = n
}

function payProducts(a, b, c,d) {
	currentUser = AV.User.current();
	var Product = AV.Object.extend('Order')
	var product = new Product();
	product.set('username', currentUser.attributes.username);
	product.set('pid', a);
	product.set('price', b);
	product.set('num',c);
	product.set('img',d);
	product.set('type', "paying");
	product.save().then(function() {
		location.href = "buynow.html"
		//		removePayProduct(a)
	}, function(error) {
		alert("failure")
	});
}